<template>
    <view class="chat">
        <scroll-view  :style="{height: `${windowHeight-inputHeight}rpx`}"
                      id="scrollview"
                      scroll-y="true"
                      refresher-background="#f2f2f2"
                      refresher-enabled="true"
                      :refresher-triggered="triggered"
                      @refresherpulling="onPulling"
                      @refresherrefresh="onRefresh"
                      @refresherabort="onAbort"
                      @refresherrestore="onRestore"
                      :scroll-top="scrollTop"
                      class="scroll-view"
        >
            <!-- 聊天主体 -->
            <view id="msglistview" class="chat-body">
                <!-- 聊天记录 -->
                <view v-for="(item,index) in msgList" :key="index">
                    <!-- 自己发的消息 -->
                    <view class="item self" v-if="item.position === 'right'" >
                        <!-- 文字内容 -->
                        <view class="content right">
                            {{item.content}}
                        </view>
                        <!-- 头像 -->
                        <view class="avatar">
                            <image mode="aspectFit" :src="item.url"/>
                        </view>
                    </view>
                    <!-- 机器人发的消息 -->
                    <view class="item Ai" v-if="item.position === 'left'">
                        <!-- 头像 -->
                        <view class="avatar">
                            <image mode="aspectFit" :src="item.url"/>
                        </view>
                        <!-- 文字内容 -->
                        <view class="content left">
                            {{item.content}}
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>
        <!-- 底部消息发送栏 -->
        <!-- 用来占位，防止聊天消息被发送框遮挡 -->
<!--        <view class="chat-bottom"  :style="{height: `${inputHeight}px`}">-->
        <view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
            <view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
                <view class="uni-textarea">
					<textarea v-model="chatMsg"
                              maxlength="300"
                              @confirm="handleSend"
                              :show-confirm-bar="false"
                              :adjust-position="false"
                              @linechange="sendHeight"
                              @focus="focus" @blur="blur"
                              auto-height/>
                </view>
                <button @touchend.prevent="handleSend" size="default" @click="handleSend" class="send-btn">发送</button>
            </view>
        </view>
    </view>
</template>
<script>
import {getHistoryMessage, sendMessageToUser} from "../../js/api/message";
import {toast} from "../../js/utils/showTip";
import webSocketClass from "../../js/utils/webSocket";
import WebSocketClas from "../../js/utils/webSocket";

export default {
    data() {
        return {
            //键盘高度
            keyboardHeight:0,
            //底部消息发送高度
            bottomHeight: 0,
            //滚动距离
            scrollTop: 0,
            userId:'',
            //发送的消息
            chatMsg:"",
            pageIndex: 1,
            pageSize: 20,
            friendUserId: 0,
            friendInfo:{},
            userinfo:{},
            msgList:[],
            triggered: false,
            toBottom: true
        }
    },
    methods: {
        focus(){
            this.scrollToBottom()
        },
        blur(){
            this.scrollToBottom()
        },
        // px转换成rpx
        rpxTopx(px){
            let deviceWidth = wx.getSystemInfoSync().windowWidth
            let rpx = ( 750 / deviceWidth ) * Number(px)
            return Math.floor(rpx)
        },
        // 监视聊天发送栏高度
        sendHeight(){
            setTimeout(()=>{
                let query = uni.createSelectorQuery();
                query.select('.send-msg').boundingClientRect()
                query.exec(res =>{
                    this.bottomHeight = this.rpxTopx(res[0].height)
                })
            },10)
        },
        // 滚动至聊天底部
        scrollToBottom(e){
            setTimeout(()=>{
                let query = uni.createSelectorQuery().in(this);
                query.select('#scrollview').boundingClientRect();
                query.select('#msglistview').boundingClientRect();
                query.exec((res) =>{
                    if(res[1].height > res[0].height){
                        this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
                    }
                })
            },15)
        },
        // 发送消息
        handleSend(event) {
            this.toBottom = true;
            //如果消息不为空
            if(!this.chatMsg||!/^\s+$/.test(this.chatMsg)){
                let requestParam = {
                    'sendUserId': this.userinfo.userId,
                    'receiveUserId': this.friendUserId,
                    'sendMessageContent': this.chatMsg
                }
                sendMessageToUser(requestParam).then(response => {
                    if (response.code !== 200) {
                        toast('发送失败！', 'error', true, 500)
                    }
                })
                this.msgList.push(
                    {
                        'url': this.userinfo.userHeadImg,
                        'nickname': this.userinfo.userNickname,
                        'content': this.chatMsg,
                        'position': 'right'
                    }
                )
                this.chatMsg = '';
                this.scrollToBottom()
                this.$nextTick(() => {
                    event.target.focus()
                })
            }
        },
        keyboardHeightChange(res) {
            //这里正常来讲代码直接写
            //this.keyboardHeight=this.rpxTopx(res.height)就行了
            //但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
            this.keyboardHeight = this.rpxTopx(res.height)
            if(this.keyboardHeight<0){
                this.keyboardHeight = 0;
            }
        },
        getHistoryMessage() {
            let requestParam = {
                'sendUserId': this.userinfo.userId,
                'receiveUserId': this.friendUserId,
                'pageIndex': this.pageIndex,
                'pageSize': this.pageSize
            }
            getHistoryMessage(requestParam).then(response => {
                if (response.code === 200) {
                    this.msgList.forEach(item => {
                        response.data.push(item)
                    })
                    this.msgList = response.data;
                    this.triggered = false;
                    this._freshing = false;
                }
            })
        },
        onPulling(e) {
        },
        onRefresh() {
            this.toBottom = false;
            if (this._freshing) {
                return;
            }
            this.triggered = true;
            this.pageIndex++;
            this.getHistoryMessage()
            this.scrollTop = 0
        },
        onRestore() {
        },
        onAbort() {
        },
        getMessage(res) {
            console.log(res)
            // let messageObj = JSON.parse(res)
            // if (this.tabbarActive === 0) {
            //     this.searchUserChatList()
            // } else {
            //     Notify({
            //         message: `${messageObj.nickname}的新消息`,
            //         type: 'primary',
            //         duration: 1500,
            //     });
            // }
        }
    },
    computed: {
        windowHeight() {
            return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
        },
        // 键盘弹起来的高度+发送框高度
        inputHeight(){
            return this.bottomHeight+this.keyboardHeight
        }
    },
    updated(){
        //页面更新时调用聊天消息定位到最底部
        if (this.toBottom) {
            this.scrollToBottom();
        } else {
            this.scrollTop = 0
        }
    },
    onLoad(option){
        // 下拉刷新状态
        this._freshing = false;
        // 当前登录用户信息
        this.userinfo = uni.getStorageSync('user');
        // 当前聊天框的好友id
        this.friendUserId = option.friendUserId
        // 获取历史消息
        this.getHistoryMessage();
        // 页面title
        uni.setNavigationBarTitle({
            title: "聊天框"
        })
        /// 监听键盘
        uni.onKeyboardHeightChange(this.keyboardHeightChange)

        // websocket监听
        let webSocket = new WebSocketClas(this.userinfo.userId);
        webSocket.connect()
        webSocket.onMessage(this.getMessage)
    },
    onUnload(){
        uni.offKeyboardHeightChange(this.keyboardHeightChange)
        uni.$off('message', this.getMessage)
    }
}
</script>
<style lang="scss" scoped>

$chatContentbgc: #00AEEF;
$sendBtnbgc: #4F7DF5;

view,button,text,input,textarea {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 聊天消息 */
.chat {
  .scroll-view {
    ::-webkit-scrollbar {
      display: none;
      width: 0 !important;
      height: 0 !important;
      -webkit-appearance: none;
      background: transparent;
      color: transparent;
    }

    // background-color: orange;
    background-color: #F6F6F6;

    .chat-body {
      display: flex;
      flex-direction: column;
      // background-color:skyblue;

      .self {
        justify-content: flex-end;
      }
      .item {
        display: flex;
        padding: 2% 2%;
        // background-color: greenyellow;

        .right {
          padding: 3%;
          background-color: $chatContentbgc;
        }
        .left {
          padding: 3%;
          background-color: #FFFFFF;
        }
        // 聊天消息的三角形
        .right::after {
          position: absolute;
          display: inline-block;
          content: '';
          width: 0;
          height: 0;
          left: 100%;
          top: 8px;
          border: 8px solid transparent;
          border-left: 8px solid $chatContentbgc;
        }

        .left::after {
          position: absolute;
          display: inline-block;
          content: '';
          width: 0;
          height: 0;
          top: 8px;
          right: 100%;
          border: 8px solid transparent;
          border-right: 8px solid #FFFFFF;
        }

        .content {
          position: relative;
          max-width: 68%;
          min-width: 13%;
          word-wrap: break-word;
          margin: 0 3%;
          border-radius: 10px;
          font-size: 97%;
          font-weight: 400;
          color: #333333;
          line-height: 180%;
        }

        .avatar {
          display: flex;
          justify-content: center;
          width: 50px;
          height: 50px;
          border-radius: 50%;
          overflow: hidden;

          image {
            align-self: center;
          }

        }
      }
    }
  }

  /* 底部聊天发送栏 */
  .chat-bottom {
    width: 100%;
    background: #F4F5F7;

    .send-msg {
      display: flex;
      align-items: flex-end;
      padding: 10% 6%;
      width: 100%;
      position: fixed;
      bottom: 0;
      background: #EDEDED;
    }

    .uni-textarea {

      textarea {
        width: 3600%;
        min-height: 25px;
        max-height: 270px;
        background: #FFFFFF;
        border-radius: 7px;
        font-size: 97%;
        color: #333333;
        line-height: 190%;
        padding: 40% 4px;
      }
    }

    .send-btn {
      border: 0px; /* 去除默认边框 */
      background: #00AEEF; /* 设置背景色为透明 */
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 86%;
      width: 70px;
      height: 40px;
      font-size: 97%;
      font-weight: 400;
      color: white;
    }
  }
}
</style>